package com.example.cc.mygit.view.language.project;

import com.example.cc.mygit.GitApplication;
import com.example.cc.mygit.model.Language;
import com.example.cc.mygit.model.Project;
import com.example.cc.mygit.source.API;
import com.haibin.elegant.Response;
import com.haibin.elegant.call.CallBack;

import java.util.List;

/**
 * Created by cc on 2016/11/23.
 */

public class LanguageProjectPresenter implements LanguageProjectContract.Presenter{

    private int mPage = 1;
    private final LanguageProjectContract.View mView;
    private Language mLanguage;

    public LanguageProjectPresenter(LanguageProjectContract.View mView,Language language) {
        this.mView = mView;
        this.mLanguage = language;
        this.mView.setPresenter(this);
    }

    @Override
    public void onRefreshing() {
        API.getProjects(GitApplication.getConfig().getUser().getPrivateToken(), mLanguage.getId(), 1, new CallBack<List<Project>>() {
            @Override
            public void onResponse(Response<List<Project>> response) {
                List<Project> items = response.getBody();
                if (items != null){
                    mView.onRefreshSuccess(items);
                    mPage = 1;
                    ++mPage;
                }
                mView.onComplete();
            }

            @Override
            public void onFailure(Exception e) {
                mView.showNetWorkError();
                mView.onComplete();

            }
        });

    }

    @Override
    public void onLoadMore() {
        API.getProjects(GitApplication.getConfig().getUser().getPrivateToken(), mLanguage.getId(), mPage, new CallBack<List<Project>>() {
            @Override
            public void onResponse(Response<List<Project>> response) {
                List<Project> items = response.getBody();
                if (items !=null){
                    mView.onLoadMoreSuccess(items);
                    ++mPage;
                    if (items.size()<20){
                        mView.showNoMoreData();
                        --mPage;
                    }
                }
                mView.onComplete();

            }

            @Override
            public void onFailure(Exception e) {
                mView.showNetWorkError();
                mView.onComplete();

            }
        });

    }

    @Override
    public void start() {

    }
}
